package lab6;

// From chapter 13 of Head First Java 2nd Ed.

import java.awt.*;
import javax.swing.*;
import javax.sound.midi.*;
import java.util.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class BeatBox extends JFrame implements ActionListener{

	private static final long serialVersionUID = 4L;
	private JPanel mainPanel;
    private ArrayList<JCheckBox> checkboxList;
    private Sequencer sequencer;
    private Sequence sequence;
    private Track track;
    private JMenuItem menuNew;
    private JMenuItem menuOpen;
    private JMenuItem menuSave;
    private final JFileChooser chooser = new JFileChooser();
    

    private String[] instrumentNames = {"Bass Drum", "Closed Hi-Hat", 
       "Open Hi-Hat","Acoustic Snare", "Crash Cymbal", "Hand Clap", 
       "High Tom", "Hi Bongo", "Maracas", "Whistle", "Low Conga", 
       "Cowbell", "Vibraslap", "Low-mid Tom", "High Agogo", 
       "Open Hi Conga"};
    private int[] instruments = {35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};
    
    public BeatBox(){
    	super("Ryan Novak, Curtis Paulson, Miezer Yang");
    }

  
    public void buildGUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        BorderLayout layout = new BorderLayout();
        JPanel background = new JPanel(layout);
        background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

        checkboxList = new ArrayList<JCheckBox>();
        Box buttonBox = new Box(BoxLayout.Y_AXIS);

        JButton start = new JButton("Start");
        start.addActionListener(new MyStartListener());
        buttonBox.add(start);         
          
        JButton stop = new JButton("Stop");
        stop.addActionListener(new MyStopListener());
        buttonBox.add(stop);

        JButton upTempo = new JButton("Tempo Up");
        upTempo.addActionListener(new MyUpTempoListener());
        buttonBox.add(upTempo);

        JButton downTempo = new JButton("Tempo Down");
        downTempo.addActionListener(new MyDownTempoListener());
        buttonBox.add(downTempo);
        
		JMenuBar menuBar = new JMenuBar();

		JMenu filemenu = new JMenu("File");
		menuBar.add(filemenu);

		menuNew = new JMenuItem("New");
		menuNew.addActionListener( this );
		filemenu.add(menuNew);

		menuOpen = new JMenuItem("Open");
		menuOpen.addActionListener( this );
		filemenu.add(menuOpen);

		menuSave = new JMenuItem("Save");
		menuSave.addActionListener( this );
		filemenu.add(menuSave);

		setJMenuBar( menuBar );

        Box nameBox = new Box(BoxLayout.Y_AXIS);
        for (int i = 0; i < 16; i++) {
           nameBox.add(new Label(instrumentNames[i]));
        }
        
        background.add(BorderLayout.EAST, buttonBox);
        background.add(BorderLayout.WEST, nameBox);

        this.getContentPane().add(background);
          
        GridLayout grid = new GridLayout(16,16);
        grid.setVgap(1);
        grid.setHgap(2);
        mainPanel = new JPanel(grid);
        background.add(BorderLayout.CENTER, mainPanel);

        for (int i = 0; i < 256; i++) {                    
            JCheckBox c = new JCheckBox();
            c.setSelected(false);
            checkboxList.add(c);
            mainPanel.add(c);            
        } // end loop

        setUpMidi();

        this.setBounds(50,50,300,300);
        this.pack();
        this.setVisible(true);
    } // close method


    public void setUpMidi() {
      try {
        sequencer = MidiSystem.getSequencer();
        sequencer.open();
        sequence = new Sequence(Sequence.PPQ,4);
        track = sequence.createTrack();
        sequencer.setTempoInBPM(120);
        
      } catch(Exception e) {e.printStackTrace();}
    } // close method

    public void buildTrackAndStart() {
      int[] trackList = null;
    
      sequence.deleteTrack(track);
      track = sequence.createTrack();

        for (int i = 0; i < 16; i++) {
          trackList = new int[16];
 
          int key = instruments[i];   

          for (int j = 0; j < 16; j++ ) {         
              JCheckBox jc = (JCheckBox) checkboxList.get(j + (16*i));
              if ( jc.isSelected()) {
                 trackList[j] = key;
              } else {
                 trackList[j] = 0;
              }                    
           } // close inner loop
         
           makeTracks(trackList);
           track.add(makeEvent(176,1,127,0,16));  
       } // close outer

       track.add(makeEvent(192,9,1,0,15));      
       try {
           sequencer.setSequence(sequence); 
	       sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);                   
           sequencer.start();
           sequencer.setTempoInBPM(120);
       } catch(Exception e) {e.printStackTrace();}
    } // close buildTrackAndStart method
            
           
    public class MyStartListener implements ActionListener {
        public void actionPerformed(ActionEvent a) {
            buildTrackAndStart();
        }
    } // close inner class

    public class MyStopListener implements ActionListener {
        public void actionPerformed(ActionEvent a) {
            sequencer.stop();
        }
    } // close inner class

    public class MyUpTempoListener implements ActionListener {
        public void actionPerformed(ActionEvent a) {
	      float tempoFactor = sequencer.getTempoFactor(); 
            sequencer.setTempoFactor((float)(tempoFactor * 1.03));
        }
     } // close inner class

     public class MyDownTempoListener implements ActionListener {
         public void actionPerformed(ActionEvent a) {
	      float tempoFactor = sequencer.getTempoFactor();
            sequencer.setTempoFactor((float)(tempoFactor * .97));
        }
    } // close inner class
 	public void actionPerformed(ActionEvent event) {
		if (event.getSource() == menuNew){
			System.out.println("New");
			
			for (int i = 0; i < 256; i++) {
				checkboxList.get(i).setSelected(false);
			}
		}
		if (event.getSource() == menuOpen){
			System.out.println("Open");
			int result = chooser.showOpenDialog(this);
			if (result == JFileChooser.APPROVE_OPTION) {
	            File file = chooser.getSelectedFile();
	            System.out.println("File chosen is: " + file.getName() );
	            try {
		            ObjectInputStream ois = new ObjectInputStream (new FileInputStream( file ));
		            ArrayList<JCheckBox> checkboxList2 = (ArrayList<JCheckBox>) ois.readObject();
		            //checkboxList = (ArrayList<JCheckBox>) ois.readObject();
		            System.out.println(" Opening BeatBox ");
		            for (int i = 0; i < 256; i++) {
						checkboxList.get(i).setSelected(checkboxList2.get(i).isSelected());
					}
		            		
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		
		if (event.getSource() == menuSave){
			System.out.println("Save");
			int result = chooser.showSaveDialog(this);
			if (result == JFileChooser.APPROVE_OPTION) {
	            File file = chooser.getSelectedFile();
	            System.out.println("File chosen is: " + file.getName() );
	            try {
	            	FileOutputStream fos = new FileOutputStream( file );
	            	ObjectOutputStream oos = new ObjectOutputStream(fos);
		            System.out.println(" Saving Beatbox ");
		            oos.writeObject(checkboxList);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

    public void makeTracks(int[] list) {        
       
       for (int i = 0; i < 16; i++) {
          int key = list[i];

          if (key != 0) {
             track.add(makeEvent(144,9,key, 100, i));
             track.add(makeEvent(128,9,key, 100, i+1));
          }
       }
    }
        
    public  MidiEvent makeEvent(int comd, int chan, int one, int two, int tick) {
        MidiEvent event = null;
        try {
            ShortMessage a = new ShortMessage();
            a.setMessage(comd, chan, one, two);
            event = new MidiEvent(a, tick);

        } catch(Exception e) {e.printStackTrace(); }
        return event;
    }

} // close class